<template>
    <div class="login">
        <!-- 顶部导航 -->
        <van-nav-bar title="登录" />

        <!-- 页面标题 -->
        <van-divider>欢迎来到node高级第三周周考</van-divider>

        <!-- 登录表单 -->
        <van-form @submit="onSubmit">
            <van-field
                v-model="form.username"
                name="username"
                placeholder="请输入账号"
                :rules="[
                    { required: true, message: '请填写用户名' },
                    {
                        validator: usernameLengthValidator,
                        message: '至少输入五位',
                        trigger: 'onChange',
                    },
                ]"
            />

            <!-- 密码 -->
            <van-field
                v-model="form.password"
                type="password"
                name="password"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />

            <div style="margin: 16px;">
                <van-button block type="info" size="small" native-type="submit">
                    登录
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script>
export default {
    data() {
        return {
            form: {
                username: '',
                password: '',
            },
        };
    },
    methods: {
        async onSubmit(values) {
            // console.log('submit', values);
            const res = await this.$http.post('/login', values);
            console.log(res);
            if (res.code !== 200) {
                this.$toast({
                    type: 'fail',
                    message: res.message,
                });
                return;
            }
            // 如果登录成功，保存 token 到 sessionStorage 里面
            window.sessionStorage.setItem('token', res.data.token);
            // 保存成功后，跳转到个人首页
            this.$router.push('/home');
        },
        usernameLengthValidator(val) {
            return val.length >= 5;
        },
    },
};
</script>

<style lang="less" scoped></style>
